<?php
//show/hide chat for individual

if (isset($_GET['enable'])) {
$user->setVar('show_chat',getVar('enable'));
?>
<meta http-equiv="Refresh" content="0; URL=<?php echo $host;?>/index.php" />
<?php
die;
}

// Delete single message
if(isset($_GET['del'])&&($user->hasAccess('chat_delete')||$user->hasAccess('chat_delete_own')))
{
    $id=getVar('del','int', true);
    if($id==null) {msg($Lang['error'], $Lang['incorrect_id'], 'error'); foot(0); die;}
    $sql->query("SELECT * FROM chat WHERE id='$id';");
    if($sql->num_rows())
    {
        $msg=$sql->fetch_array();
        if($user->hasAccess('chat_delete') ||($user->hasAccess('chat_delete_own') && $msg['user']==$user->getUser()))
        {
            $sql->query( "DELETE FROM chat WHERE id='$id'");
        }
        else
        {
            msg($Lang['error'], $Lang['no_access'], 'error'); foot(0); die;
        }
    }
    else
    {
        msg($Lang['error'], $Lang['message_not_found'], 'error'); foot(0); die;
    }
}
// Empty all
if (isset($_GET['delall'])&&$user->hasAccess('chat_delete_all'))
{
    $sql->query("TRUNCATE TABLE chat;");
}
// Edit message
if ((isset($_GET['edit'])||isset($_POST['text'])) && ($user->hasAccess('chat_edit')||$user->hasAccess('chat_edit_own')))
{	
    $id=(isset($_GET['edit'])?getVar('edit', 'int',true): getVar('id','int',true));
    $sql->query("SELECT id, user, text FROM chat WHERE id='$id';");
    if($sql->num_rows())
    {
        $msg=$sql->fetch_array();
        if($user->hasAccess('chat_edit') || ($user->hasAccess('chat_edit_own')&&$msg['user']==$user->getUser()))
        {
            if(isset($_POST['text']))
            {
                $text = trim(getVar('text'));
                $sql->query("UPDATE chat SET text = '$text' WHERE id='$id';");
            }
            else
            {
                echo '<form method="post" action="'.$host.'/index.php?p=chat&no_head">
                <input type="hidden" name="id" value="'.$msg['id'].'" />
                <textarea name="text" rows="3">'.htmlspecialchars($msg['text']).'</textarea><br />
                <input type="submit" name="save" value="'.$Lang['save'].'" /></form>';
                die;
            }
        }
        else
        {
            msg($Lang['error'],$Lang['no_access'], 'error');
            die;
        }
    }
    else
    {
        msg($Lang['error'],$Lang['message_not_found'], 'error');
        die;
    }
}
//== begin main output
$HTMLOUT .="
<style type='text/css'>

</style>";

if (!$user->hasAccess('chat_chat'))
{
    msg($Lang['error'], $Lang['no_access'], 'error');
    die;
}

if ( isset( $_POST['sent'] ) && ( $_POST['sent'] == "yes" ) ) {
    $limit = 20;
    $usern = $user->getUser();
    $date = time();
    $text = getVar("chbox_text");
    $system_pattern = '/(^\/system)\s([\w\W\s]+)/is';
	if(preg_match($system_pattern,$text,$out) && $user->hasAcces('chat_system'))
	{
		$usern = "System";
		$text = $out[2];
	}
	 
  	$private_pattern = "/(^\/private)\s([a-zA-Z0-9]+)\s([\w\W\s]+)/";
    if(preg_match($private_pattern,$text,$vars)) {
		$to_user = $sql->result($sql->query('select id from employees WHERE user = '.$sql->escape($vars[2])),0);
		if($to_user != 0 && $to_user != $CURUSER['id']) {
			$text = $vars[2]." - ".$vars[3];
			$sql->query( "INSERT INTO chat (user, date, text, to_user) VALUES ('$usern', '$date', '$text', '$to_user')");
		}		
        $HTMLOUT .="<script type=\"text/javascript\">parent.document.forms[0].chbox_text.value='';</script>";
	} else {
	   $check_flood_q=$sql->query( "SELECT user,date FROM chat ORDER by id DESC LIMIT 1 " );
       if($sql->num_rows($check_flood_q))
       {
            $a = $sql->fetch_array($check_flood_q);
       }
        
        if ( empty( $text ) || strlen( $text ) == 1 )
            $HTMLOUT .="<font class=\"small\" color=\"red\">{$Lang['message_empty']}</font>";
        elseif ($a!=null && $a['user'] == $userid && ( time() - $a['date'] ) < $limit )
            $HTMLOUT .="<font class=\"small\" color=\"red\">$limit seconds between shouts <font class=\"small\">Seconds Remaining : (" . ( $limit - ( time() - $a['date'] ) ) . ")</font></font>";
        else {
            $sql->query( "INSERT INTO chat (user, date, text) VALUES ('$usern', '$date', '$text');" );
            $HTMLOUT .="<script type=\"text/javascript\">parent.document.forms[0].chbox_text.value='';</script>";
        }
    }
}
// //////////////////////
$res = $sql->query( "SELECT c.id, c.user, c.date , c.text, c.to_user, e.name FROM chat as c LEFT JOIN employees as e ON c.user=e.user ORDER BY c.date DESC LIMIT 30" );
if (!$sql->num_rows($res))
    $HTMLOUT .=$Lang['no_messages'];
else {
   $HTMLOUT .="<table border='0' cellspacing='0' cellpadding='2' width='100%' align='left' class='small'>\n";
		$gotpm = 0;
        
    while ($arr=$sql->fetch_array($res))
    {
    	if(($arr['to_user'] != $user->getUser() && $arr['to_user'] != 0) && $arr['user'] != $user->getUser()) 
    		continue;
    	elseif($arr['to_user'] == $user->getUser() || ($arr['user'] == $user->getUser() && $arr['to_user'] !=0) )
    		$private = "<a href=\"javascript:private_reply('".$arr['name']."')\"><img src=\"img/private-chat.png\" alt=\"{$Lang['private_chat']}\" title=\"{$Lang['click_to_reply']} {$arr['name']}\" width=\"16\" style=\"padding-left:2px;padding-right:2px;\" border=\"0\" /></a>";
    	else
    		$private = '';
            $edit = ($user->hasAccess('chat_edit') || ($user->hasAccess('chat_edit_own')&&$arr['user'] == $user->getUser()) ? "<a href='$host/index.php?p=chat&no_head&edit=" . $arr['id']."'><img src='img/edit.png' border='0' alt=\"{$Lang['edit_chat']}\"  title=\"{$Lang['edit_chat']}\" /></a> " : "" );
            $del = ( $user->hasAccess('chat_delete') || ($user->hasAccess('chat_delete_own') && $arr['user']==$user->getUser()) ? "<a href='index.php?p=chat&no_head&del=" . $arr['id'] . "'><img src='img/delete.png' border='0' alt=\"{$Lang['delete_single_chat']}\" title=\"{$Lang['delete_single_chat']}\" /></a> " : "" );
                  
            
            $date = get_date_time($arr["date"]);
            $user_stuff = $arr;
            $user_stuff['id'] = $arr['user'];
            $HTMLOUT .="<tr><td><span class='size1'>[$date]</span>\n$del $edit $private <a href='$host/user.php?id=" . $arr["user"] . "' target='_blank'><font color='#" . $user->getColor() . "'>" . htmlspecialchars( $arr['name'] ) . "</font></a><span class='size2'> " . format_comment( $arr["text"] ) . "\n</span></td></tr>";
    }
    $HTMLOUT .="</table>";
}
$HTMLOUT .="</body></html>";
print $HTMLOUT;

?>